package com.wushi.lenovo.asia5b.app_utils

import android.content.Context
import android.net.ConnectivityManager
import com.wushi.lenovo.asia5b.app_config.dddBug
import java.lang.Exception

/**
 * Created by zhangyuncai on 2020/6/24.
 */
object ConnectUtils {
    /**
     * 是否有活动的网络
     */
    fun isConnect(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetworkInfo = connectivityManager.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnected;
    }

    /**
     * 是否打开移动网络开关
     */
    fun isMobileEnable(context: Context): Boolean {
        var isMobileConn: Boolean = true
        try {
            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val getMobileDataEnabledMethod = ConnectivityManager::class.java.getDeclaredMethod("getMobileDataEnabled")
            getMobileDataEnabledMethod.isAccessible = true
            isMobileConn = getMobileDataEnabledMethod.invoke(connectivityManager) as Boolean
        } catch (e: Exception) {
            e.printStackTrace()
        }
        // 反射失败，默认开启
        dddBug("isMobileEnable:${isMobileConn}")
        return isMobileConn
    }

    /**
     * 是否打开WIFI开关
     */
    fun isWifiEnable(context: Context): Boolean {
        val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        var isWifiConn: Boolean = false
        connMgr.allNetworks.forEach { network ->
            connMgr.getNetworkInfo(network).apply {
                if (type == ConnectivityManager.TYPE_WIFI) {
                    isWifiConn = isWifiConn or isConnected
                }
            }
        }

        // 默认关闭
        dddBug("isWifiEnable:${isWifiConn}")
        return isWifiConn
    }
}